package com.ict.conf;

import com.ict.encrypt.CustomEncryptorConfig;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

/**
 * Jasypt配置类注入，可以自动解密ENC()配置
 */
@Configuration
public class JasyptConfig {

    private String crack;

    @Bean(name = "jasyptStringEncryptor")
    public StringEncryptor stringEncryptor() {
        try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("jasypt/crack.key")) {
            if (inputStream == null) {
                throw new RuntimeException("Could not find the crack.key file in the specified directory.");
            }

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
                this.crack = reader.lines().collect(Collectors.joining("\n"));
            }

        } catch (Exception e) {
            throw new RuntimeException("Failed to load the crack.key file", e);
        }
        return new CustomEncryptorConfig(crack);
    }
}
